# -*- coding: utf-8 -*-
# @时间：2023/11/2 19:54
# @作者：CJiaの可乐哥
# @文件名：login
# @软件：Pycharm2023
import time

from django.core.cache import cache
from django.forms import model_to_dict
from django.shortcuts import get_object_or_404
from ninja import Router, Schema, ModelSchema
from config.env import USER_OBJ
from system.models import Users, UserRole, UserPost, RolePermission
from utils.cj_md5 import md5_pass
from utils.request_util import save_login_log
from utils.cj_jwt import create_token, parse_payload
from utils.usual import get_user_info
from utils.cj_response import SuccessResponse, ErrorResponse

router = Router()


class UserSchemaOut(ModelSchema):
    roles: list = []
    posts: list = []
    permissions: list = []

    class Config:
        model = Users
        model_exclude = ['password']


class LoginSchemaIn(Schema):
    username: str = None
    password: str = None


class LoginSchemaOut(Schema):
    userInfo: UserSchemaOut
    token: str = None


@router.post("/login", response=LoginSchemaOut, auth=None)
def login(request, data: LoginSchemaIn):
    data.password = md5_pass(data.password)
    print(md5_pass(data.password))
    user_obj = Users.objects.filter(username=data.username, password=data.password).first()
    if user_obj:
        request.user = user_obj
        token = create_token({'id': user_obj.id, 'username': user_obj.username, 'is_superuser': user_obj.is_superuser,
                              'key': int(time.time())},
                             60)
        user_obj_dic = model_to_dict(user_obj)
        del user_obj_dic['password']
        data = {
            'userInfo': user_obj,
            'token': f'Bearer {token}',
        }
        save_login_log(request=request)
        return data
    else:
        request.user = USER_OBJ
        return ErrorResponse(msg="账号或密码错误")


@router.post("/logout")
def logout(request):
    token = request.META.get("HTTP_AUTHORIZATION")
    token = token.replace('Bearer ', "")
    user = parse_payload(token)
    # 刪除缓存
    cache.delete_pattern(user['data']['username'] + str(user['data']['key']))
    return SuccessResponse(msg="注销成功")


@router.get("/userinfo", response=UserSchemaOut)
def userinfo(request):
    user = get_object_or_404(Users, username=request.username)
    return get_user_info(user.id)
